package com.itheia.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheia.common.R;
import com.itheia.domain.Book;
import com.itheia.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Jijinhao
 * @since 2022-09-12
 */
@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private IBookService bookService;

    // 查
    @GetMapping
    public R getAll() {
        List<Book> list = bookService.list();
        return R.success(list);
    }

    // 查一个
    @GetMapping("/{id}")
    public R getByID(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        return R.success(book);
    }

    // 增
    @PostMapping
    public R save(@RequestBody Book book) {
        boolean b = bookService.save(book);
        return b ? R.success("success") : R.error("error");
    }

    // 删
    @DeleteMapping("/{id}")
    public R delete(@PathVariable Long id) {
        boolean b = bookService.removeById(id);
        return b ? R.success("success") : R.error("error");
    }

    // 改
    @PutMapping
    public R update(@RequestBody Book book) {
        LambdaQueryWrapper<Book> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(book.getId() != null, Book::getId, book.getId());
        boolean b = bookService.update(book, wrapper);
        return b ? R.success("success") : R.error("error");
    }



}

